<?php

namespace App\Http\Controllers\Mini;

use App\Http\Controllers\Home\PaymentController;
use App\Models\ActivityCategorys;
use App\Models\Activitys;
use App\Models\AdminAgencys;
use App\Models\Ads;
use App\Models\Areas;
use App\Models\Buys;
use App\Models\Collections;
use App\Models\Configs;
use App\Models\Footprints;
use App\Models\IntegralLogs;
use App\Models\Mails;
use App\Models\SignUps;
use App\Models\Stores;
use App\Models\UserInfos;
use App\Models\Users;
use App\Models\Wechat;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ActivityController extends Controller
{
    /**
     * 活动分类
     * @route api.act.actCate
     */
    public function actCate(Request $request){
        try{
            $lists = ActivityCategorys::getCascaderList();
            $fields = ['id','thumb','title','enroll_at','start_at','end_at','view','cost','number','cate_pid','cate_id'];
            $now_time = date('Y-m-d H:i:s');
            foreach ($lists as $k=>$v){//获取分类下的热门活动、最新活动
                $lists[$k]['hot'] = Activitys::allLists(['hot'=>2,'cid'=>$v['value'],'status'=>1],$fields, null,3,'number');
                $lists[$k]['new'] = Activitys::allLists(['cid'=>$v['value'],'status'=>1],$fields, null,3, 'created_at');
                foreach ($lists[$k]['hot'] as $key=>$val){
                    $lists[$k]['hot'][$key]['view'] = strlen($val['view'])>=4 ? '999+' : $val['view'];
                    $lists[$k]['hot'][$key]['number'] = strlen($val['number'])>=4 ? '999+' : $val['number'];
                    $lists[$k]['hot'][$key]['start_at'] = trim(@date('Y-m-d', strtotime($val['start_at'])));
                    $lists[$k]['hot'][$key]['enroll_at'] = trim(@date('Y-m-d', strtotime($val['enroll_at'])));
                    $lists[$k]['hot'][$key]['end_at'] = trim(@date('Y-m-d', strtotime($val['end_at'])));
                    if($now_time <= $val['enroll_at']){
                        $lists[$k]['hot'][$key]['act_state'] = '报名中';
                    }elseif ($now_time >= $val['start_at']){
                        $lists[$k]['hot'][$key]['act_state'] = '已举办';
                    }else{
                        $lists[$k]['hot'][$key]['act_state'] = '报名结束';
                    }
                }
                foreach ($lists[$k]['new'] as $key=>$val){
                    $lists[$k]['new'][$key]['view'] = strlen($val['view'])>=4 ? '999+' : $val['view'];
                    $lists[$k]['new'][$key]['number'] = strlen($val['number'])>=4 ? '999+' : $val['number'];
                    $lists[$k]['new'][$key]['start_at'] = trim(@date('Y-m-d', strtotime($val['start_at'])));
                    $lists[$k]['new'][$key]['enroll_at'] = trim(@date('Y-m-d', strtotime($val['enroll_at'])));
                    if($now_time <= $val['enroll_at']){
                        $lists[$k]['new'][$key]['act_state'] = '报名中';
                    }elseif ($now_time >= $val['start_at']){
                        $lists[$k]['new'][$key]['act_state'] = '已举办';
                    }else{
                        $lists[$k]['new'][$key]['act_state'] = '报名结束';
                    }
                }
                //获取分类下的广告
                $params = [
                    'adsense_id' => 35,
                    'status' => 1,
                ];
                $lists[$k]['adv'] = Ads::getList($params, ['id','adsense_id','thumb','link','target']);
            }

            return response()->json(["code" => 1, "msg" => "获取成功", "data" => $lists]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 活动筛选
     * @route api.act.actScreen
     */
    public function actScreen(Request $request){
        try{
            $lists = [];
            $lists['cate'] = ActivityCategorys::getCascaderList();
            $lists['area'] = Areas::where('status','<>',-1)->orderBy('sort','asc')->get(['id','name']);//服务区域

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 活动列表
     * @route api.act.actLists
     * @param content 热搜词条
     * @param cid_id 二级分类id
     * @param page 页码
     * @param limit 条数
     * @param sid 排序 1收藏量 2浏览量 3报名量
     */
    public function actLists(Request $request){
        try{
            $cid_pid = $request->post('cid_pid');//一级分类id
            $cid_id = $request->post('cid_id');//二级分类id
            $map['keyword'] = $request->post('content');//搜索词条
            if (!empty($cid_pid)){
                $map['cid_pid'] = explode(",", $cid_pid);
            }else {
                $map['cid_pid'] = null;
            }
            if (!empty($cid_id)){
                $map['cid_id'] = explode(",", $cid_id);
            }else {
                $map['cid_id'] = null;
            }
            $map['status'] = 1;
            $page = (int)$request->post('page',1);//页码
            $limit = (int)$request->post('limit',5);//条数
            $sid = (int)$request->post('sid');//排序 1收藏量 2浏览量 3报名量
            if ($sid == 1){
                $sort = 'collect';
            }elseif ($sid == 2){
                $sort = 'view';
            }elseif ($sid == 3){
                $sort = 'number';
            }else{
                $sort = 'created_at';
            }
            $fields = ['id','thumb','title','start_at','view','cost','number','enroll_at','start_at','end_at','cate_pid','cate_id'];
            $lists = Activitys::allLists($map, $fields, $page, $limit, $sort, 'desc');
            $now_time = date('Y-m-d H:i:s');
            foreach ($lists as $key=>$val){
                $lists[$key]['view'] = strlen($val['view'])>=4 ? '999+' : $val['view'];
                $lists[$key]['number'] = strlen($val['number'])>=4 ? '999+' : $val['number'];
                $lists[$key]['start_at'] = trim(@date('Y-m-d', strtotime($val['start_at'])));
                $lists[$key]['enroll_at'] = trim(@date('Y-m-d', strtotime($val['enroll_at'])));
                $lists[$key]['end_at'] = trim(@date('Y-m-d', strtotime($val['end_at'])));
                if($now_time <= $val['enroll_at']){
                    $lists[$key]['act_state'] = '报名中';
                }elseif ($now_time >= $val['start_at']){
                    $lists[$key]['act_state'] = '已举办';
                }else{
                    $lists[$key]['act_state'] = '报名结束';
                }
            }

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 活动详情
     * @route api.act.actDetails
     * @param user_id 用户id
     * @param act_id 活动id
     * @return is_act 0:不可报名 1:可报名
     * @return is_collect 0:未收藏 1:已收藏
     * @return is_sign_up 0:未报名 1:已报名
     */
    public function actDetails(Request $request){
        try{
            $user_id = (int)$request->post('user_id');
            $user_info = Users::where('id',$user_id)->where('status','<>',-1)->first();

            $act_id = (int)$request->post('act_id');//活动id
            if (empty($act_id)) return response()->json(["code"=>0, "msg"=>'参数错误']);

            $now_time = date('Y-m-d H:i:s');
            $lists = Activitys::details(['id'=>$act_id], ['*']);
            $lists['view'] = strlen($lists['view'])>=4 ? '999+' : $lists['view'];
            $lists['number'] = strlen($lists['number'])>=4 ? '999+' : $lists['number'];
            $lists['is_act'] = 1;//默认可报名
            if($now_time <= $lists['enroll_at']){
                $lists['act_state'] = '报名中';
                $lists['is_act'] = 1;//可报名
            }elseif ($now_time >= $lists['start_at']){
                $lists['act_state'] = '已举办';
                $lists['is_act'] = 0;//不可报名
            }else{
                $lists['act_state'] = '报名结束';
                $lists['is_act'] = 0;//不可报名
            }
            //判断是否收藏和报名
            $lists['is_collect'] = 0;//默认未收藏
            $lists['is_sign_up'] = 0;//默认未报名
            if (!empty($user_info)){
                if($user_info['type'] == 1){
                    //收藏
                    $collect = Collections::where(['collect_id'=>$act_id,'user_id'=>$user_info['id'],'type'=>5])->value('collect_id');
                    $lists['is_collect'] = empty($collect) ? 0 : 1;
                    //报名
                    $sign_up = SignUps::where(['activity_id'=>$act_id, 'user_id'=>$user_info['id']])->where('status','<>',-1)->value('activity_id');
                    $lists['is_sign_up'] = empty($sign_up) ? 0 : 1;
                }
                //添加足迹
                $foot_arr = [
                    'user_id' => $user_info['id'],
                    'foot_id' => $act_id,
                    'type'    => 4,
                ];
                $foot_id = Footprints::where($foot_arr)->value('id');
                if($foot_id > 0){
                    Footprints::where($foot_arr)->update(['updated_at'=>date('Y-m-d H:i:s')]);
                }else{
                    Footprints::create($foot_arr);
                }
            }
//            //主办方信息
//            if($lists['source'] == 1){
//                $base = Configs::getConfig('base');
////                $lists['store'] = ['logo'=>$base['site_logo'], 'name'=>$lists['sponsor'], 'link_phone'=>$base['customer_mobile']];
//                $lists['link_phone'] = $base['customer_mobile'];
//            }
//            else if ($lists['source'] == 2){
//                $fields = ['id','user_id','store_name','logo','cate_id','call','credit','collections','area_info','view','hot','quality'];
//                $store = Stores::details(['user_id'=>$lists['user_id']], $fields);
//                $store['call'] = strlen($store['call'])>=4 ? '999+' : $store['call'];
//                $store['collections'] = strlen($store['collections'])>=4 ? '999+' : $store['collections'];
//                //获取当前店铺所属用户的区域
//                $area_id = Users::where('id',$store['user_id'])->where('status','<>',-1)->value('area');
//                $store['area'] = Areas::where('id',$area_id)->where('status','<>',-1)->value('name');
//                //二级分类
//                if (!empty($store['cate_id'])){
//                    $store['cate_id'] = explode(',',$store['cate_id']);
//                    foreach ($store['cate_id'] as $k => $v){
//                        $pidTree[] =Categorys::where('id',$v)->first('name');
//                    }
//                }else{
//                    $pidTree['name'] = [];
//                }
//                $store['cate_id'] = $pidTree;
//                //判断是否收藏
//                $store['store_collect'] = 1;//默认未收藏
//                if (!empty($userinfo) && $userinfo['type'] == 1){
//                    $collect = Collections::where(['collect_id'=>$act_id,'user_id'=>$userinfo['id'],'type'=>4])->value('collect_id');
//                    $store['store_collect'] = empty($collect) ? 1 : 2;
//                }
//                $lists['store'] = $store;
//            }
            Activitys::where('id',$act_id)->increment('view');//浏览量加1

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 收藏活动
     * @route api.act.actCollect
     * @param user_id 用户id
     * @param collect_id 收藏内容id
     */
    public function actCollects(Request $request){
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录!']);
            $userinfo = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['type','status']);
            if (empty($userinfo)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }else{
                if($userinfo['status'] == 2){
                    return response()->json(["code"=>0, "msg"=>'账户正在审核中，请等待审核!']);
                }elseif($userinfo['status'] == 3){
                    return response()->json(["code"=>0, "msg"=>'账号未通过审核，请前往个人中心查看原因并重新提交审核!']);
                }elseif ($userinfo['status'] == 4){
                    return response()->json(["code"=>0, "msg"=>'账号已锁定，请前往个人中心查看原因或联系客服!']);
                }
                if ($userinfo['type'] != 1) return response()->json(["code"=>0, "msg"=>'供应商不能收藏活动!']);
            }

            $collect_id = (int)$request->post('collect_id');
            if (empty($collect_id)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            $collect = Collections::where(['collect_id'=>$collect_id, 'user_id'=>$user_id, 'type'=>5])->value('id');
            if (empty($collect)){
                $params = [
                    'collect_id' => $collect_id,
                    'user_id' => $user_id,
                    'collect_at' => date('Y-m-d H:i:s'),
                    'type' => 5,
                ];
                Collections::create($params);
                Activitys::where('id',$collect_id)->increment('collect');
                return response()->json(["code"=>1, "msg"=>'收藏成功']);
            }else {
                Collections::where(['collect_id'=>$collect_id, 'user_id'=>$user_id, 'type'=>5])->delete();
                return response()->json(["code"=>1, "msg"=>'取消收藏成功']);
            }
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * HR报名活动
     * @route api.act.actSignUp
     * @param user_id 用户id
     * @param activity_id 活动id
     * @param number 参与人数
     * @param type 类型：1收费 2免费
     * @param money 总价
     * @param price 单价
     */
    public function actSignUp(Request $request){
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $userinfo = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['id','username','sex','mobile','email','type','status','openid']);
            if (empty($userinfo)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }else{
                if($userinfo['status'] == 2){
                    return response()->json(["code"=>0, "msg"=>'账户正在审核中，请等待审核!']);
                }elseif($userinfo['status'] == 3){
                    return response()->json(["code"=>0, "msg"=>'账号未通过审核，请前往个人中心查看原因并重新提交审核!']);
                }elseif ($userinfo['status'] == 4){
                    return response()->json(["code"=>0, "msg"=>'账号已锁定，请前往个人中心查看原因或联系客服!']);
                }
                if ($userinfo['type'] != 1) return response()->json(["code"=>0, "msg"=>'供应商不能报名活动!']);
                $more = UserInfos::where('user_id',$user_id)->value('company_name');
                if ($more == null) return response()->json(["code"=>0, "msg"=>'您还未完善信息，请前往个人中心完善信息后再发布!']);
            }

            $activity_id = (int)$request->post('activity_id');//活动id
            $number = (int)$request->post('number');//参与人数
            $type = (int)$request->post('type');//类型：1收费 2免费
            if (empty($activity_id) || empty($number) || empty($type)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            $act = Activitys::where('id',$activity_id)->where('status','<>',-1)->first(['title','id','cost','charge','limit','number','enroll_at','start_at','place']);
            $now_time = date('Y-m-d H:i:s');
            if (empty($act)){
                return response()->json(["code"=>0, "msg"=>'此活动不存在']);
            }else{
                if (($now_time > $act['enroll_at'] && $now_time < $act['start_at']) || $act['limit'] == $act['number']){
                    return response()->json(["code"=>0, "msg"=>'此活动已结束报名']);
                }elseif ($now_time >= $act['start_at']){
                    return response()->json(["code"=>0, "msg"=>'此活动已举办']);
                }
            }
            //判断报名人数
            $numbers = $act['limit'] - $act['number'];
            if ($numbers <= 0){
                return response()->json(["code"=>0, "msg"=>'此活动报名人数已满,请选择其他活动报名']);
            }elseif ($number > $numbers){
                return response()->json(["code"=>0, "msg"=>'此活动目前最多只能报名'.$numbers.'人,请重新选择报名人数']);
            }

            $sign_up = SignUps::where(['user_id'=>$user_id,'activity_id'=>$activity_id,'pay_state'=>2])->value('id');
            if (!empty($sign_up)) return response()->json(["code"=>0, "msg"=>'您已报名此活动']);

            $money = (float)$request->post('money');//总价
            $price = (float)$request->post('price');//单价

            $params = [
                'pay_sn' => Buys::makePaySn($activity_id),
                'activity_id' => $activity_id,
                'activity_title' => $act['title'],
                'user_id' => $user_id,
                'user_name' => $userinfo['username'],
                'sex' => $userinfo['sex'],
                'phone' => $userinfo['mobile'],
                'email' => $userinfo['email'],
                'company' => $userinfo['user_info']['company_name'],
                'department' => $userinfo['user_info']['hr_department'],
                'position' => $userinfo['user_info']['hr_position'],
                'type' => $userinfo['user_info']['company_type'],
                'industry' => $userinfo['user_info']['company_industry'],
                'size' => $userinfo['user_info']['company_size'],
                'hr_size' => $userinfo['user_info']['hr_size'],
                'number' => $number,
            ];
            if($type == 2){//免费
                $params['money'] = 0;
                $params['price'] = 0;
                $params['charge'] = 2;
                $params['pay_state'] = 2;
                $params['pay_at'] = date('Y-m-d H:i:s');
            }elseif ($type == 1){//收费
                $params['money'] = $money;
                $params['price'] = $price;
                //TOOD
            }
            $sign_info = SignUps::create($params);
            //生成未处理数据给后台
            $maps = [
                'title' => '未处理活动订单：'.$params['user_name'],
                'type' => 6,
            ];
            AdminAgencys::create($maps);
            if($sign_info['charge'] == 1){
                //根据订单信息，生成支付二维码
                $order_info = SignUps::where(array('pay_sn'=>$sign_info['pay_sn']))->first();
                $order_act = Activitys::where(array('id'=>$order_info['activity_id']))->first();
                $detail = $order_act['title'].'支付订单';
                $notify_url = route('home.payment.actNotifyUrl');
                $payment = new PaymentController();
                $openId = Users::where('id',$user_id)->value('openid');
                $ret = $payment->wxPayment($sign_info['pay_sn'], $order_info['activity_id'],(float)$order_info['money'],'支付订单',$detail,$notify_url,'JSAPI',$openId);
                if($ret['code'] == 1){
                    return response()->json(["code"=>1, "msg"=>'报名订单生成成功', "data"=>$ret]);
                }else{
                    return response()->json(["code"=>0, "msg"=>'报名订单生成失败', "data"=>$ret]);
                }
            } else{
                $integrals = Configs::getConfig('integral');
                Activitys::where('id',$params['activity_id'])->increment('number',$number);//报名人数加1
                Users::where('id',$user_id)->increment('integral',$integrals['hr_activity']);//报名活动送积分
                //添加日志记录
                $integral = [
                    'user_id' => $user_id,
                    'user_name' => $userinfo['username'],
                    'integral' => '+'.$integrals['hr_activity'],
                    'type' => 1,
                    'desc' => '报名活动送积分',
                ];
                IntegralLogs::create($integral);
                //发送站内信-积分增加通知
                $template = [
                    'title' => '报名活动获得积分',
                    'content' => '您报名活动获得"' . $integrals['hr_activity'] .'"积分',
                    'user_id' => $user_id,
                    'status' => 1,
                    'type' => 1,
                ];
                Mails::create($template);
                //报名成功、推送微信消息
                if (!empty($userinfo['openid'])){
                    $template_id = 'W4F_jcLE6buTbjGnYLBxb7xz2DvpWUuuQL0-gX0WEA0';
                    $url = 'http://wap.hrqidian.com/#/myActive';
                    $data = [
                        'first' => '您已成功报名<'.$act['title'].'>活动，小启非常重视这次活动',
                        'keyword1' => $act['title'],
                        'keyword2' => $act['start_at'],
                        'keyword3' => $act['place'],
                        'remark' => '请您仔细查看活动要求按时参加，如有变化请第一时间通知活动举办者。 HR小启客服',
                    ];
                    Wechat::wechatSend($userinfo['openid'], $template_id, $url, $data);
                }
                return response()->json(["code"=>1, "msg"=>'报名成功', 'data'=>$activity_id]);
            }
        }
        catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 活动报名结果
     * @route api.act.actSignUpResult
     * @param act_id 活动id
     */
    public function actSignUpResult(Request $request){
        try{
            $act_id = (int)$request->post('act_id');//活动id
            if (empty($act_id)) return response()->json(["code"=>0, "msg"=>'参数错误']);

            $lists = Activitys::details(['id'=>$act_id], ['id','title','cost','charge','cate_pid','cate_id']);

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

}